package com.chee.plant.logic.user;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;

import com.chee.plant.hibernate.dao.EmailDAO;
import com.chee.plant.hibernate.object.Email;
import com.chee.plant.logic.CmdHandler;
import com.chee.plant.logic.PlantCmd;
import com.chee.plant.server.Message;

/**
 * 显示用户站内信
 * 
 * @author xue cb
 * 
 */
public class ShowUserEmailHandler implements CmdHandler {

	@Override
	public Vector<Message> executeCmd(Message msg) {
		// 要返回的内容
		Vector<Message> _msgs = new Vector<Message>();
		// 解析客户端传过来的内容
		int userId = msg.getUserId();
		// 从数据库查询用户站内信
		List<Email> list = new EmailDAO().getEmailByUserId(userId);
		int result = 1;
		// 构造Message对象
		Message ret = new Message(userId, PlantCmd.GetUserEmail, result);

		List<JSONObject> emailList = new ArrayList<JSONObject>();

		Iterator<Email> iterator = list.iterator();

		while (iterator.hasNext()) {
			Email email = iterator.next();
			JSONObject obj = new JSONObject();
			try {
				obj.append("id", email.getId());
				obj.append("owner_id", email.getOwnerId());
				obj.append("from_id", email.getFromId());
				obj.append("to_id", email.getToId());
				obj.append("title", email.getTittle());
				obj.append("content", email.getContent());
				obj.append("created", email.getCreated());
			} catch (JSONException e) {
				// 添加JSON 格式错误处理
				e.printStackTrace();
			}

			emailList.add(obj);
		}
		ret.addVariable("list", emailList);
		_msgs.add(ret);
		return _msgs;

	}

}
